//
//  ByNetBase.m
//  beibei_ios
//
//  Created by hebidu on 16/4/15.
//  Copyright © 2016年 hebidu. All rights reserved.
//

#import "ByNetBaseApi.h"
#import "ByCoreCryptDes.h"

#import "ByNetBaseResponse.h"           // 返回model
#import "ByNetBaseError.h"              // 错误model



#define UPLOAD_ERROR_STRING_CODE -67
#define UPLOAD_ERROR_OTHER_CODE -76

@implementation ByNetBaseApi

/** 返回数据是否是正确的 */
+ (BOOL)returnDataIsCurrect:(id)data type:(ByNetDataType)type {
    
    switch (type) {
        case ByNetDataTypeString:
        {
            if ([data isKindOfClass:[NSString class]]) {
                return YES;
            } else {
                return NO;
            }
        }
            break;
        case ByNetDataTypeArray:
        {
            if ([data isKindOfClass:[NSArray class]]) {
                return YES;
            } else {
                return NO;
            }
        }
            break;
        case ByNetDataTypeDictionary:
        {
            if ([data isKindOfClass:[NSDictionary class]]) {
                return YES;
            } else {
                return NO;
            }
        }
            break;
        default:
            break;
    }
}

#pragma mark - post请求
/**
 *  post请求
 *  @param requestId 请求ID，随机字符串，可用时间戳
 *  @param apiType    请求接口类型（什么请求，登录？注册？。。。）
 *  @param apiVerson 请求接口版本
 *  @param params      明文参数（账号，密码等）内部进行加密
 *  @param success result：解密后的数据（一般为字典）
 *  @param failure
 */
+ (void)post:(NSString *)requestId
     apiType:(NSString *)type
    dataType:(ByNetDataType)dataType
   apiVerson:(NSInteger)ver
      params:(NSDictionary *)params
     success:(void(^)(NSURLSessionDataTask *operation, id result, NSString *notifyID))success
     failure:(void(^)(NSURLSessionDataTask *operation, NSError *error))failure {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    // 默认超时时间30秒
    manager.requestSerializer.timeoutInterval = 10;
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json", @"text/json", @"text/javascript", nil];
    
    [manager.requestSerializer setValue:@"SocketLog(tabid=2&client_id=slog_fc68e9)" forHTTPHeaderField:@"SocketLog"];
    
    // 数据加密
    NSMutableDictionary *m_params = [[NSMutableDictionary alloc] initWithDictionary:params];
    
    NSMutableDictionary *dic = [self getData:requestId apiType:type apiVerson:ver params:m_params];
    NSLog(@"%@",dic);
    
    // 再des 传输结构加密
    NSMutableDictionary *post = [self desCrypt:dic];

    NSString *urlStr = [BOYE_BASE_URL stringByAppendingFormat:@"?lang=zh-cn&client_id=%@&alg=md5_v2",BOYE_CLIENT_ID];
    
    [manager POST:urlStr
       parameters:post
         progress:^(NSProgress * uploadProgress){
         }
          success:^(NSURLSessionDataTask *operation ,id responseObject) {
              @try {
                  /** 返回数据为字典 则继续做操作，否则错误回调 */
                  if ([responseObject isKindOfClass:[NSDictionary class]]) {
                      
                      ByNetBaseResponse *response = [[ByNetBaseResponse alloc] initWithDic:responseObject trueType:dataType];
                      [response setFailourBlock:^(NSString *errorDesc, NSInteger code) {
                          
                          [self operateFailure:failure errorDesc:errorDesc code:code];
                      }];
                      [response setSuccessBlock:^(id data, NSString *notifyID) {
                          if (success) {
                              success(operation, data, notifyID);
                          }
                      }];
                      [response dataAnalysis];
                      
                  }
                  /** 返回数据不为字典，数据错误 */
                  else {
                      [self operateFailure:failure errorDesc:@"服务器异常!请重试" code:-101];
                  }
              } @catch (NSException *exception) {
                  DLog(@"异常操作,reason:%@", exception.reason);
              }
              
          } failure:^(NSURLSessionDataTask *operation , NSError *error){
              
              ByNetBaseError *errorModel = [[ByNetBaseError alloc] initWithError:error];
              [errorModel setFailourBlock:^(NSString *errorDesc, NSInteger code) {
                  [self operateFailure:failure errorDesc:errorDesc code:code];
              }];
              [errorModel errorAnalysis];
          }];
}



/** 统一处理错误时的信息 */
+ (void)operateFailure:(void(^)(NSURLSessionDataTask *operation, NSError *error))failure
             errorDesc:(NSString *)desc
                  code:(NSInteger)code {
    
    if (failure) {
        NSError *error = [[NSError alloc] initWithDomain:desc code:code userInfo:nil];
        failure(nil, error);
    } else {
        [ByCoreToolAlert showFailureWithText:desc];
    }
}


+ (BOOL)failureProcess:(NSError * )error{
    
    if (error.code == NSURLErrorTimedOut) {
        [ByCoreToolAlert showFailureWithText:@"请求超时!"];
        return YES;
    }
    if(error.code == NSURLErrorBadURL) {
        [ByCoreToolAlert showFailureWithText:@"非法请求地址!"];
        return YES;
    }
    if(error.code == NSURLErrorCannotFindHost) {
        [ByCoreToolAlert showFailureWithText:@"无法查找远程主机!"];
        return YES;
    }
    if(error.code == NSURLErrorCannotConnectToHost) {
        [ByCoreToolAlert showFailureWithText:@"远程主机无法连接!"];
        return YES;
    }
    if([error.domain isEqualToString: @"NSURLErrorDomain"]) {
        [ByCoreToolAlert showFailureWithText:@"请求失败,请重试!"];
        return YES;
    }
    
    return NO;
}


+(NSMutableDictionary * ) desCrypt:(id)param{
    
    NSString *jsonString;
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:param options:NSJSONWritingPrettyPrinted error:&error];
    
    if (!jsonData) {
        NSLog(@"byit____Got an error: %@", error);
    } else {
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    NSMutableDictionary * tmp = [[NSMutableDictionary alloc]init];
    
    NSString * postDes =  [ByCoreCryptDes desEncode:jsonString :BOYE_CLIENT_SECRET];
    
    [tmp setObject: [ByCoreCrypt base64Encode:postDes] forKey:@"itboye"];
    [tmp setObject: @"itboye" forKey:@"copyright"];

    return tmp;
}


+(NSMutableDictionary *) getData:(NSString *)requestId
                         apiType:(NSString *)type
                       apiVerson:(NSInteger)ver
                          params:(NSDictionary *)params{
    NSMutableDictionary * dic = [[NSMutableDictionary alloc] init];
    
    NSNumber * timestamp = [NSNumber numberWithDouble:[NSDate currentDateTimeInterval]];
    
    NSString * time = [NSString stringWithFormat:@"%ld",timestamp.integerValue];
    
    [dic setValue:time forKey:@"time"]; // 时间戳参数
    
    [dic setValue:requestId forKey:@"notify_id"]; //
    
    // 如果没有业务参数（params == nil，则在加密中做了处理
    NSString *dataStr;
    dataStr = [ByCoreCrypt encryptString:params]; // 明文参数加密
    
    
    [dic setValue:@"md5" forKey:@"alg"]; // 加密方式
    
    [dic setValue:dataStr forKey:@"data"]; // 加密后的数据参数
    [dic setValue:type forKey:@"type"]; // 请求类型参数
    [dic setValue:@(ver) forKey:@"api_ver"]; // 版本号，和服务器一样才能返回正确数据
    
    
    NSArray *numAry = [APP_VERSION componentsSeparatedByString:@"."];
    
    NSInteger versionNum = [numAry[0] integerValue] * 10000 + [numAry[1] integerValue] * 100 + [numAry[2] integerValue];
    [dic setValue:@(versionNum) forKey:@"app_version"]; // 版本号
    [dic setValue:@"ios" forKey:@"app_type"]; // 类型
    
    NSString *signStr = [ByCoreCrypt signData:dic];
    [dic setValue:signStr forKey:@"sign"]; // 签名
    return dic;
}



//#pragma mark - 图片上传
//// 上传单个图片（头像）
//+ (void)uploadImage:(UIImage *)image
//               type:(NSString *)type
//            success:(void(^)(NSArray *success))success
//            failure:(void(^)(NSURLSessionDataTask *operation, NSError *error))failure {
//    
//    // 构造请求参数
//    ByNetUserModel *user = [ByCommonCache getUserInfo];
//    if(user == nil) return;
//    
//    // manager对象
//    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//    manager.requestSerializer = [AFJSONRequestSerializer serializer];
//    manager.requestSerializer.timeoutInterval = 10;
//    // AFN序列化，接收内容类型为以下这些
//    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
//    
//    // 构造网址
//    NSString *strUrl = [NSString stringWithFormat:@"%@/file/upload?client_id=%@&uid=%@&type=%@",BOYE_API_URL, BOYE_CLIENT_ID,user.uid,type];
//    
//    // 处理图片
//    NSData *data = UIImageJPEGRepresentation(image, 1);
//    while ((data.length / 1000.0) > 500) {
//        UIImage *tmp_image = [UIImage imageWithData:data];
//        data = UIImageJPEGRepresentation(tmp_image, 0.5);
//    }
//    
//    // 拼接请求体
//    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:strUrl  parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//        [formData appendPartWithFileData:data name:@"image" fileName:@"icon.jpg" mimeType:@"image/jpeg"];
//        
//    } error:nil];
//    
//    
//    NSURLSessionUploadTask *uploadTask;
//    uploadTask = [manager
//                  uploadTaskWithStreamedRequest:request
//                  progress:^(NSProgress * _Nonnull uploadProgress) {
//                      
//                      NSLog(@"fractionCompleted: %f", uploadProgress.fractionCompleted);
//                      
//                      // 根据请求进度刷新UI
//                      dispatch_async(dispatch_get_main_queue(), ^{
//                      });
//                      
//                  }
//                  completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
//                      if (error) {
//                          NSLog(@"Error: %@", error);
//                          
//                          if (failure) {
//                              failure(nil, error);
//                          }
//                      } else {
//                          NSLog(@"upload:%@", responseObject);
//                          
//                          NSDictionary *responseDic = responseObject;
//                          if (![responseObject[@"data"] isKindOfClass:[NSArray class]]) {
//                              NSError *error;
//                              if ([responseObject[@"data"] isKindOfClass:[NSString class]]) {
//                                  error = [NSError errorWithDomain:responseObject[@"data"] code:UPLOAD_ERROR_STRING_CODE userInfo:nil];
//                              } else {
//                                  error = [NSError errorWithDomain:@"未知错误!请重试" code:UPLOAD_ERROR_OTHER_CODE userInfo:nil];
//                              }
//                              if (failure) {
//                                  failure(nil, error);
//                              }
//                          } else {
//                              NSArray *ary = responseDic[@"data"];
//                              if (success) {
//                                  success(ary);
//                              }
//                          }
//                          
//                      }
//                  }];
//    
//    [uploadTask resume];
//}
//
//+ (void)uploadImages:(NSArray *)images
//                type:(NSString *)type
//             success:(void (^)(NSArray *success))success
//             failure:(void (^)(NSURLSessionDataTask *, NSError *))failure {
//    
//    // 构造请求参数
//    ByNetUserModel *user = [ByCommonCache getUserInfo];
//    if(user == nil){
//        return;
//    }
//    // manager对象
//    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//    manager.requestSerializer = [AFJSONRequestSerializer serializer];
//    manager.requestSerializer.timeoutInterval = 20;
//    // AFN序列化，接收内容类型为以下这些
//    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
//    
//    NSDictionary *params;
//    if ([type containsString:@"&"]) {
//        NSArray *temp = [type componentsSeparatedByString:@"&"];
//        params = @{@"uid":user.uid,
//                    @"type":temp[0],
//                   @"house_no":temp[1],};
//    } else {
//        params = @{@"uid":user.uid,
//                   @"type":type};
//    }
//    
//    
//    NSString *url = [NSString stringWithFormat:@"%@/File/upload?client_id=%@",BOYE_API_URL, BOYE_CLIENT_ID];
//    
//    // 处理图片
//    NSMutableArray *tmp = [[NSMutableArray alloc] initWithArray:images];
//    for (int i = 0; i < tmp.count; i ++) {
//        NSData *data = UIImageJPEGRepresentation(images[i], 1);
//        while ((data.length / 1000.0) > 500) {
//            UIImage *tmp_image = [UIImage imageWithData:data];
//            data = UIImageJPEGRepresentation(tmp_image, 0.5);
//        }
//        NSLog(@"大小:%likb", data.length / 1000);
//        [tmp replaceObjectAtIndex:i withObject:data];
//        
//    }
//    
//    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//        
//        for (int i = 0; i < tmp.count; i ++) {
//            [formData appendPartWithFileData:tmp[i] name:@"image[]" fileName:[NSString stringWithFormat:@"pic%i.jpg", i] mimeType:@"image/jpeg"];
//        }
//        
//    } error:nil];
//    
//    
//    
//    NSURLSessionUploadTask *uploadTask;
//    uploadTask = [manager
//                  uploadTaskWithStreamedRequest:request
//                  progress:^(NSProgress * _Nonnull uploadProgress) {
//                      
//                      NSLog(@"fractionCompleted: %f", uploadProgress.fractionCompleted);
//                      
//                      
//                      
//                      dispatch_async(dispatch_get_main_queue(), ^{
//                      });
//                  }
//                  completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
//                      if (error) {
//                          NSLog(@"Error:%@", error);
//                          NSLog(@"Error_response:%@", responseObject);
//
//                          if (failure) {
//                              failure(nil, error);
//                          }
//                      } else {
//                          NSLog(@"upload:%@", responseObject);
//                          
//                          NSDictionary *responseDic = responseObject;
//                          if (![responseObject[@"data"] isKindOfClass:[NSArray class]]) {
//                              NSError *error;
//                              if ([responseObject[@"data"] isKindOfClass:[NSString class]]) {
//                                  error = [NSError errorWithDomain:responseObject[@"data"] code:UPLOAD_ERROR_STRING_CODE userInfo:nil];
//                              } else {
//                                  error = [NSError errorWithDomain:@"未知错误!请重试" code:UPLOAD_ERROR_OTHER_CODE userInfo:nil];
//                              }
//                              if (failure) {
//                                  failure(nil, error);
//                              }
//                          } else {
//                              NSArray *dataAry = responseDic[@"data"];
//                              if (success) {
//                                  success(dataAry);
//                              }
//                          }
//                          
//                      }
//                  }];
//    
//    [uploadTask resume];
//    
//}

@end
